
import pandas as pd
import Core.Label as Label
import Core.Gadget as Gadget
import Core.MongoDB as MongoDB
import numpy as np
import json
import Core.Portfolio as Portfoio
import Core.DataSeries as DataSeries
import Core.Algorithm as Algorithm
import Core.IO as IO
import datetime
import math
import random as rd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from Talent import NetValue as nv

# import Algorithm
import matplotlib.dates as mdate
import time

def StockList():
    trades = database.find("Instruments", "Stock")
    symbols = []
    for trade in trades:
        symbol = trade["Symbol"]
        symbols.append(symbol)
    return symbols

def FamaAnalyse(datetime1,datetime2):

    symbols = StockList()
    Style = {}
    filter = {}
    filter["StdDateTime"] = {}
    filter["StdDateTime"]["$gte"] = datetime1
    filter["StdDateTime"]["$lte"] = datetime2
    filter["Symbol"] = "000300.SH"
    csi300 = database.Find("Index", "DailyBar", filter)
    dates = []
    for i in range(len(csi300)):
        dates.append(csi300[i]["StdDateTime"])
    j = 0
    while j < len(dates):
        if j == 1:
            debug = 1
        datetime_cal = dates[j]
        for symbol in symbols:
            if symbol == "000001.SZ":
                debig = 1
            factor = {}
            datetime_before = datetime_cal - datetime.timedelta(days=200)
            filter["StdDateTime"] = {}
            filter["StdDateTime"]["$gte"] = datetime_before
            filter["StdDateTime"]["$lte"] = datetime_cal
            filter["Symbol"] = symbol
            quotes = database.Find("Stock", "DailyBar", filter)
            debug = 1
            if len(quotes) <= 2:
                continue
            quote = quotes[len(quotes) - 1]
            quote_lastday = quotes[len(quotes) - 2]
            factors = database.find("Factor", "BookToMarket", datetime_before, datetime_cal, query={"Symbol": symbol})
            if not factors:
                continue
            factor = factors[- 1]
            if symbol not in Style:
                doc = {}
                doc["Symbol"] = symbol
                doc["StdDateTime"] = quote["StdDateTime"]
                doc["Price"] = quote["Close"] / quote["AdjFactor"]
                doc["Return"] = (quote["Close"] / quote["AdjFactor"]) / (
                            quote_lastday["Close"] / quote_lastday["AdjFactor"]) - 1
                doc["AdjFactor"] = 1
                doc["BTM"] = factor["Value"]
                doc["MV"] = quote["Close"] * quote["Values"]["TotalShares"]
                Style[symbol] = doc
            Style[symbol]["Price"] = quote["Close"] / quote["AdjFactor"]
            Style[symbol]["BTM"] = factor["Value"]
            Style[symbol]["AdjFactor"] = quote["AdjFactor"]
            Style[symbol]["MV"] = quote["Close"] * quote["Values"]["TotalShares"]
            Style[symbol]["Return"] = (quote["Close"] / quote["AdjFactor"]) / (
                        quote_lastday["Close"] / quote_lastday["AdjFactor"]) - 1
            Style[symbol]["StdDateTime"] = quote["StdDateTime"]


        df = pd.DataFrame(columns=('Symbol', 'Return', 'BTM', "MV"))  # 生成空的pandas表
        i = 0
        for symbol in Style:  # 插入一行
            df.loc[i] = [Style[symbol]["Symbol"], Style[symbol]["Return"], Style[symbol]["BTM"], Style[symbol]["MV"]]
            i += 1

        df_order_by_BTM = df.sort_values(by=["BTM"])
        df_order_by_MV = df.sort_values(by=["MV"])
        stocks_low_BTM = df_order_by_BTM[0:(math.floor(len(df) / 2) - 1)]  # 索引需要注意：pandas前闭后开，包括前不包括后
        stocks_high_BTM = df_order_by_BTM[math.floor(len(df) / 2) - 1:(len(df))]
        stocks_small_MV = df_order_by_MV[0:math.floor(len(df) / 2) - 1]
        stocks_big_MV = df_order_by_MV[math.floor(len(df) / 2) - 1:len(df)]
        Return_on_size = stocks_small_MV.iloc[0:len(stocks_small_MV), 1].mean() - stocks_big_MV.iloc[
                                                                                  0:len(stocks_big_MV), 1].mean()
        Return_on_BTM = stocks_high_BTM.iloc[0:len(stocks_high_BTM), 1].mean() - stocks_low_BTM.iloc[
                                                                                 0:len(stocks_low_BTM), 1].mean()
        # print(stocks_high_BTM.iloc[0:len(stocks_high_BTM),1])
        # print(stocks_low_BTM.iloc[0:len(stocks_lo0w_BTM),1])#索引需要注意：pandas前闭后开，包括前不包括后

        print(IO.ToDateString(Style[symbol]["StdDateTime"]), Return_on_size, Return_on_BTM,len(df))

        j += 1

def RegressionAnalyse(datetime1,datetime2,ID, Model):
    data = pd.read_csv(r'C:\Users\zhujunheng\Desktop\fama.csv',header=None,sep=',',names=["date",'size_return','value_return','market_return','no_of_stocks','account','account_return'],dtype = {'date' : str})
    packageIds = ID
    accounts = database.find("Talent", "Account", datetime1, datetime2, query={"Portfolio": packageIds})

    i = 0
    while i < len(data):
        for account in accounts:
            if data.iloc[i , 0] == IO.ToDateString3(account["StdDateTime"]):
                data.iloc[i , 5] = account["Value"]
                if i > 0:
                    if data.iloc[i - 1, 5] != np.nan:
                        data.iloc[i, 6] = (data.iloc[i, 5] - data.iloc[i - 1, 5]) / data.iloc[i - 1, 5]
        i = i + 1
    data = data.dropna()
    data[['size_return','value_return','market_return']] = data[['size_return' ,'value_return','market_return']].apply(pd.to_numeric)

    ######相关性分析
    if Model == "Fama":
        x = data.iloc[:, 1:4]
    elif Model == "CAPM":
        x = data.iloc[:, 3]

    y = data.iloc[:, 6]
    #x1 = data.iloc[:, 1:3]
    a = y.iloc[:].sum()
    #print(a)
    if a == 0:
        print(ID, "None" , "None"  "Not Trading" )
        return

    x = sm.add_constant(x)
    #x1 = sm.add_constant(x1)
    #print(x)
    #print(y)
    #data.to_csv(r'C:\Users\zhujunheng\Desktop\fama1.csv')
    est = sm.OLS(y, x).fit()
    #est1 = sm.OLS(y, x1).fit()
    dict_name = GetTalentName()
    for symbol in dict_name:
        if symbol == ID:
            ID_name = dict_name[symbol]["UserName"]
            if est.params.iloc[0] <= 0:
                continue
    if Model == "Fama":
        print(ID, ID_name, est.params.iloc[0], est.pvalues.iloc[0], est.params.iloc[1], est.pvalues.iloc[1],
              est.rsquared)
    elif Model == "CAPM":
        print(ID, ID_name, est.params.iloc[0], est.pvalues.iloc[0], est.params.iloc[1], est.pvalues.iloc[1],
              est.rsquared)



    #print (est.summary())


def StyleBox(datetime1,datetime2,packageId,positionfile):

    symbols = StockList()
    #symbols = symbols[0:300]
    Style = {}
    filter = {}
    filter["StdDateTime"] = {}
    filter["StdDateTime"]["$gte"] = datetime1
    filter["StdDateTime"]["$lte"] = datetime2
    filter["Symbol"] = "000300.SH"
    csi300 = database.Find("Index", "DailyBar", filter)
    dates = []
    for i in range(len(csi300)):
        dates.append(csi300[i]["StdDateTime"])
    datetime_cal = datetime2
    for symbol in symbols:
        factor = {}
        datetime_before = datetime_cal - datetime.timedelta(days=30)
        quotes = database.find("Quote", symbol + "_Time_86400_Bar", datetime_before, datetime_cal)
        if len(quotes) <= 2:
            continue
        quote = quotes[len(quotes) - 1]
        quote_lastday = quotes[len(quotes) - 2]
        factors = database.find("Factor", "BookToMarket", datetime_cal - datetime.timedelta(days=300), datetime_cal, query={"Symbol": symbol})
        if not factors:
            continue
        factor = factors[len(factors) - 1]
        if symbol not in Style:
            doc = {}
            doc["Symbol"] = symbol
            doc["StdDateTime"] = quote["StdDateTime"]
            doc["Price"] = quote["Close"] / quote["AdjFactor"]
            doc["AdjFactor"] = 1
            doc["BTM"] = factor["Value"]
            doc["MV"] = quote["Close"] * quote["Values"]["TotalShares"]
            Style[symbol] = doc
        Style[symbol]["Price"] = quote["Close"] / quote["AdjFactor"]
        Style[symbol]["BTM"] = factor["Value"]
        Style[symbol]["AdjFactor"] = quote["AdjFactor"]
        Style[symbol]["MV"] = quote["Close"] * quote["Values"]["TotalShares"]
        Style[symbol]["StdDateTime"] = quote["StdDateTime"]

    df = pd.DataFrame(columns=('Symbol', 'BTM', "MV", "Style"))  # 生成空的pandas表
    i = 0
    for symbol in Style:  # 插入一行
        df.loc[i] = [Style[symbol]["Symbol"], Style[symbol]["BTM"], Style[symbol]["MV"], ["None"]]
        i += 1

    df_order_by_BTM = df.sort_values(by=["BTM"])
    df_order_by_MV = df.sort_values(by=["MV"])
    print(len(df_order_by_MV))
    i=0
    while i<math.floor(len(df) * 0.3)-1:
        df_order_by_BTM.iloc[i,3] = "Low BTM"  # 索引需要注意：pandas前闭后开，包括前不包括后
        df_order_by_MV.iloc[i,3] = "Small MV"
        i+=1
    print(i)

    while i<math.floor(len(df) * 0.7)-1:
        df_order_by_BTM.iloc[i, 3] = "Medium BTM"  # 索引需要注意：pandas前闭后开，包括前不包括后
        df_order_by_MV.iloc[i, 3] = "Medium MV"
        i += 1
    print (i)
    while i<len(df):
        df_order_by_BTM.iloc[i, 3] = "High BTM"  # 索引需要注意：pandas前闭后开，包括前不包括后
        df_order_by_MV.iloc[i, 3] = "Big MV"
        i += 1
    print(i)
    #print(df_order_by_BTM)
    #print(df_order_by_MV)
    package_id_list = []
    packageIds = packageId
    for package_id in packageIds:
        package_id_list.append({"Portfolio": package_id})

    filter = {"$or": package_id_list}
    positions = database.find("Talent", positionfile, query=filter)
    position_HighBTM_BigMV = 0
    position_HighBTM_MediumMV = 0
    position_HighBTM_SmallMV = 0
    position_MediumBTM_BigMV = 0
    position_MediumBTM_MediumMV = 0
    position_MediumBTM_SmallMV = 0
    position_LowBTM_BigMV = 0
    position_LowBTM_MediumMV = 0
    position_LowBTM_SmallMV = 0
    for position in positions:
        a = 12

        index1 = df_order_by_BTM[df_order_by_BTM.Symbol.isin([position["Symbol"]])]
        index2 = df_order_by_MV[df_order_by_MV.Symbol.isin([position["Symbol"]])]
        if len(index1) > 0 and len(index2) > 0:
            #print(index1["Style"],index2["Style"])
            quotes = database.find("Quote", position["Symbol"] + "_Time_86400_Bar", datetime_cal - datetime.timedelta(days=60),
                                   datetime2)
            quote = quotes[len(quotes)-1]
            if index1["Style"].any() == "High BTM" and index2["Style"].any() == "Big MV":
                position_HighBTM_BigMV += position["Qty"]* quote["Close"]
            elif index1["Style"].any() == "High BTM" and index2["Style"].any() == "Medium MV":
                position_HighBTM_MediumMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "High BTM" and index2["Style"].any() == "Small MV":
                position_HighBTM_SmallMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "Medium BTM" and index2["Style"].any() == "Big MV":
                position_MediumBTM_BigMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "Medium BTM" and index2["Style"].any() == "Medium MV":
                position_MediumBTM_MediumMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "Medium BTM" and index2["Style"].any() == "Small MV":
                position_MediumBTM_SmallMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "Low BTM" and index2["Style"].any() == "Big MV":
                position_LowBTM_BigMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "Low BTM" and index2["Style"].any() == "Medium MV":
                position_LowBTM_MediumMV += position["Qty"] * quote["Close"]
            elif index1["Style"].any() == "Low BTM" and index2["Style"].any() == "Small MV":
                position_LowBTM_SmallMV += position["Qty"] * quote["Close"]
    total = position_HighBTM_BigMV + position_HighBTM_MediumMV + position_HighBTM_SmallMV + position_MediumBTM_BigMV + position_MediumBTM_MediumMV + position_MediumBTM_SmallMV + position_LowBTM_BigMV + position_LowBTM_MediumMV + position_LowBTM_SmallMV

    print(position_HighBTM_BigMV / total, position_HighBTM_MediumMV / total, position_HighBTM_SmallMV / total)
    print(position_MediumBTM_BigMV / total,position_MediumBTM_MediumMV / total,position_MediumBTM_SmallMV / total)
    print(position_LowBTM_BigMV / total,position_LowBTM_MediumMV / total,position_LowBTM_SmallMV / total)

        #print(df_order_by_BTM[index,  "Style"])

def StyleOfIndex(datetime1,datetime2,Benchmark_index):

    symbols = StockList()
    #symbols = symbols[0:300]
    Style = {}
    filter = {}
    filter["StdDateTime"] = {}
    filter["StdDateTime"]["$gte"] = datetime1
    filter["StdDateTime"]["$lte"] = datetime2
    filter["Symbol"] = "000300.SH"
    csi300 = database.Find("Index", "DailyBar", filter)
    dates = []
    for i in range(len(csi300)):
        dates.append(csi300[i]["StdDateTime"])
    datetime_cal = datetime2
    for symbol in symbols:
        factor = {}
        datetime_before = datetime_cal - datetime.timedelta(days=30)
        quotes = database.find("Quote", symbol + "_Time_86400_Bar", datetime_before, datetime_cal)
        if len(quotes) <= 2:
            continue
        quote = quotes[len(quotes) - 1]
        quote_lastday = quotes[len(quotes) - 2]
        factors = database.find("Factor", "BookToMarket", datetime_cal - datetime.timedelta(days=300), datetime_cal, query={"Symbol": symbol})
        if not factors:
            continue
        factor = factors[len(factors) - 1]
        if symbol not in Style:
            doc = {}
            doc["Symbol"] = symbol
            doc["StdDateTime"] = quote["StdDateTime"]
            doc["Price"] = quote["Close"] / quote["AdjFactor"]
            doc["AdjFactor"] = 1
            doc["BTM"] = factor["Value"]
            doc["MV"] = quote["Close"] * quote["Values"]["TotalShares"]
            Style[symbol] = doc
        Style[symbol]["Price"] = quote["Close"] / quote["AdjFactor"]
        Style[symbol]["BTM"] = factor["Value"]
        Style[symbol]["AdjFactor"] = quote["AdjFactor"]
        Style[symbol]["MV"] = quote["Close"] * quote["Values"]["TotalShares"]
        Style[symbol]["StdDateTime"] = quote["StdDateTime"]

    df = pd.DataFrame(columns=('Symbol', 'BTM', "MV", "Style"))  # 生成空的pandas表
    i = 0
    for symbol in Style:  # 插入一行
        df.loc[i] = [Style[symbol]["Symbol"], Style[symbol]["BTM"], Style[symbol]["MV"], ["None"]]
        i += 1

    df_order_by_BTM = df.sort_values(by=["BTM"])
    df_order_by_MV = df.sort_values(by=["MV"])
    print(len(df_order_by_MV))
    i=0
    while i<math.floor(len(df) * 0.3)-1:
        df_order_by_BTM.iloc[i,3] = "Low BTM"  # 索引需要注意：pandas前闭后开，包括前不包括后
        df_order_by_MV.iloc[i,3] = "Small MV"
        i+=1
    print(i)

    while i<math.floor(len(df) * 0.7)-1:
        df_order_by_BTM.iloc[i, 3] = "Medium BTM"  # 索引需要注意：pandas前闭后开，包括前不包括后
        df_order_by_MV.iloc[i, 3] = "Medium MV"
        i += 1
    print (i)
    while i<len(df):
        df_order_by_BTM.iloc[i, 3] = "High BTM"  # 索引需要注意：pandas前闭后开，包括前不包括后
        df_order_by_MV.iloc[i, 3] = "Big MV"
        i += 1
    print(i)
    #print(df_order_by_BTM)
    #print(df_order_by_MV)
    package_id_list = []
    packageIds = packageId
    for package_id in packageIds:
        package_id_list.append({"Portfolio": package_id})

    filter = {"$or": package_id_list}
    positions = database.find("Instruments", "InstrumentList", datetime_cal - datetime.timedelta(days=600), datetime_cal, query={"Symbol": Benchmark_index})
    positions = positions[len(positions)-1]
    a = positions["Values"][1]["Symbol"]
    position_HighBTM_BigMV = 0
    position_HighBTM_MediumMV = 0
    position_HighBTM_SmallMV = 0
    position_MediumBTM_BigMV = 0
    position_MediumBTM_MediumMV = 0
    position_MediumBTM_SmallMV = 0
    position_LowBTM_BigMV = 0
    position_LowBTM_MediumMV = 0
    position_LowBTM_SmallMV = 0
    i = 0
    while i< len(positions["Values"]):
        index1 = df_order_by_BTM[df_order_by_BTM.Symbol.isin([positions["Values"][i]["Symbol"]])]
        index2 = df_order_by_MV[df_order_by_MV.Symbol.isin([positions["Values"][i]["Symbol"]])]
        if len(index1) > 0 and len(index2) > 0:

            if index1["Style"].any() == "High BTM" and index2["Style"].any() == "Big MV":
                position_HighBTM_BigMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "High BTM" and index2["Style"].any() == "Medium MV":
                position_HighBTM_MediumMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "High BTM" and index2["Style"].any() == "Small MV":
                position_HighBTM_SmallMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "Medium BTM" and index2["Style"].any() == "Big MV":
                position_MediumBTM_BigMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "Medium BTM" and index2["Style"].any() == "Medium MV":
                position_MediumBTM_MediumMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "Medium BTM" and index2["Style"].any() == "Small MV":
                position_MediumBTM_SmallMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "Low BTM" and index2["Style"].any() == "Big MV":
                position_LowBTM_BigMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "Low BTM" and index2["Style"].any() == "Medium MV":
                position_LowBTM_MediumMV += positions["Values"][i]["Weight"]
            elif index1["Style"].any() == "Low BTM" and index2["Style"].any() == "Small MV":
                position_LowBTM_SmallMV += positions["Values"][i]["Weight"]
        i += 1
    total = position_HighBTM_BigMV + position_HighBTM_MediumMV + position_HighBTM_SmallMV + position_MediumBTM_BigMV + position_MediumBTM_MediumMV + position_MediumBTM_SmallMV + position_LowBTM_BigMV + position_LowBTM_MediumMV + position_LowBTM_SmallMV

    print(position_HighBTM_BigMV / total, position_HighBTM_MediumMV / total, position_HighBTM_SmallMV / total)
    print(position_MediumBTM_BigMV / total,position_MediumBTM_MediumMV / total,position_MediumBTM_SmallMV / total)
    print(position_LowBTM_BigMV / total,position_LowBTM_MediumMV / total,position_LowBTM_SmallMV / total)

        #print(df_order_by_BTM[index,  "Style"])

def TalentHoldings(datetime1,datetime2,packageId,positionfile):
    total_value = 0
    Talentholdings = {}
    UTCtime = Gadget.ToUTCDateTime(datetime2)
    UTCtime = datetime2 - datetime.timedelta(hours=9)
    print(Gadget.ToDate(datetime2))
    print("持有股票", "持有份额", "市值", "每股价格","成本价","持仓盈亏","持仓比例")
    for i in range(len(packageId)):
        ID = packageId[i]
        positions = database.find("Talent", positionfile, query={"Portfolio": ID})
        accounts = database.find("Talent", "Account", query={"Portfolio": ID, "StdDateTime": UTCtime})
        account = accounts[-1]

        total_value += account["Value"]

        if len(positions) > 0:
            for j in range(len(positions)):
                symbol = positions[j]["Symbol"]
                if positions[j]["Qty"] == 0:
                    continue
                quotes = database.find("Quote", symbol + "_Time_86400_Bar",
                                       datetime2 - datetime.timedelta(days=100), datetime2)
                quote = quotes[-1]
                if symbol not in Talentholdings:
                    doc = {}
                    doc["Qty"] = positions[j]["Qty"]
                    doc["Cost"] = positions[j]["Cost"]

                    doc["Price"] = quote["Close"]
                    doc["Value"] = doc["Qty"] * doc["Price"]
                    Talentholdings[symbol] = doc
                    debug = 1
                elif symbol in Talentholdings:
                    Talentholdings[symbol]["Qty"] = Talentholdings[symbol]["Qty"] + positions[j]["Qty"]
                    Talentholdings[symbol]["Value"] = Talentholdings[symbol]["Qty"] * Talentholdings[symbol]["Price"]
                    debug = 1
    for symbol in Talentholdings:
        profit = Talentholdings[symbol]["Value"] - Talentholdings[symbol]["Cost"]
        print(symbol, Talentholdings[symbol]["Qty"], Talentholdings[symbol]["Value"] ,Talentholdings[symbol]["Value"]/total_value)
    print("牛人计划总资产： ", total_value)



def GetTalentList():
    trades = database.find("Talent", "Portfolio")
    list = []
    for trade in trades:
        list.append(trade["Name"])
    return list

def GetTalentName():
    trades = database.find("Talent", "Portfolio")
    Names = {}
    for trade in trades:
        symbol = trade["Name"]
        if symbol not in Names:
            doc={}
            doc["UserName"]= trade["UserName"]
            Names[symbol] = doc
    return Names

def AlphaOfTalents(datetime1, datetime2 , Talent_list, Model):
    print("ID", "Name", "Alpha", "P-value", "Beta", "P-value", "R2")
    for i in range(len(Talent_list)):
        ID = Talent_list[i]
        trades = database.find("Talent", "Trade", datetime1, datetime2, query={"Portfolio": ID})
        if len(trades) == 0:
            continue
        if trades[-1]["StdDateTime"] < datetime2 - datetime.timedelta(days=100):
            continue
            #剔除一百日内无交易的
        if trades[0]["StdDateTime"] > datetime2 - datetime.timedelta(days=365):
            continue
            #剔除初次交易未满一年的
        #if len(trades) < 10:
            #continue
            #剔除总交易少于五十笔的
        RegressionAnalyse(datetime1, datetime2, ID, Model)

def AlphaOfTalentsSum(Talent_list,datetime1,datetime2):
    data = pd.read_csv(r'C:\Users\zhujunheng\Desktop\fama.csv', header=None, sep=',',
                       names=["date", 'size_return', 'value_return', 'market_return', 'no_of_stocks', 'account',
                              'account_return'], dtype={'date': str})
    packageIds = Talent_list
    accounts = nv.GetAccount(Talent_list,datetime1,datetime2)
    i = 0
    while i < len(data):
        data.iloc[i, 5] = accounts[data.iloc[i, 0]]["Value"]
        if i > 0:
            if data.iloc[i - 1, 5] != np.nan:
                data.iloc[i, 6] = (data.iloc[i, 5] - data.iloc[i - 1, 5]) / data.iloc[i - 1, 5]
        i = i + 1
    data = data.dropna()
    data[['size_return', 'value_return', 'market_return']] = data[
        ['size_return', 'value_return', 'market_return']].apply(pd.to_numeric)

    ######相关性分析
    x = data.iloc[:, 1:4]
    y = data.iloc[:, 6]
    # x1 = data.iloc[:, 1:3]
    a = y.iloc[:].sum()
    # print(a)
    if a == 0:
        print("None", "None"  "Not Trading")
        return
    x = sm.add_constant(x)
    est = sm.OLS(y, x).fit()
    print("Alpha", "P-value", "Beta", "P-value", "R2")
    print(est.params.iloc[0], est.pvalues.iloc[0], est.params.iloc[3], est.pvalues.iloc[3],
          est.rsquared)
    # print (est.summary())

from Core.Config import Config
config = Config()
database = config.DataBase()
packageId_16 = ["12126", "11303", "12230","11147","12340","12044","11354","11556","12495","11500","12279","11370","12308","11738","12334","12341"]
packageId_26 = ["12126","11303","12230","11147", "12340", "12044", "11354", "11556", "12495", "11500", "12279", "11370",
"12308","11738", "12334", "12341", "12304", "11313","12404", "12103","11175","11251","12419","11373","12036","12195"]
packageId = packageId_16
datetime1 = datetime.datetime(2017, 5, 2)
datetime1 = Gadget.ToUTCDateTime(datetime1)
datetime2 = datetime.datetime(2018, 11, 30)
datetime2 = Gadget.ToUTCDateTime(datetime2)
datetime3 = datetime.datetime(2018, 11, 16)
datetime3 = Gadget.ToUTCDateTime(datetime3)

#StyleBox(datetime1,datetime2,packageId_16,"Position20181129") #牛人持仓风格分析
#FamaAnalyse(datetime3 ,datetime2) #更新市场因子，价值因子，和公司规模因子，需要手动输入至fama1文件里
AlphaOfTalents(datetime1, datetime2 , GetTalentList(),"Fama")#全部牛人各自的阿尔法计算(Fama  CAPM 两种模型可以选择)
#AlphaOfTalentsSum(packageId_26,datetime1,datetime2) #牛人计划阿尔法
#TalentHoldings(datetime1,datetime2,packageId_16,"Position20181129")


#StyleOfIndex(datetime1,datetime2,"000300.SH") #测试大盘指数持仓风格

